<div id="terminInfo">
    <div id="terminInfoHeader">Informacje o terminie</div>
    <div id="terminInfoContent">wybierz jakiś termin</div>
</div>
<div class="form wide">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'wizyta-form',
	'enableAjaxValidation'=>false,
    ));

    function phpTerminyToJsArray($input) {
        $js = "var terminy = new Array();";

        foreach($input as $i=>$day) {
            $js .= "var result_1 = new Array();";
            foreach($day as $j=>$time) {
                $js .= "var result_2 = new Array();";
                foreach($time as $l=>$val) {
                    $js .= "result_2[".$l."] = '".$val."';";
                }
                $js .= "result_1[".$j."] = result_2;";
            }
            $js .= "terminy[".$i."] = result_1;";
        }

        return $js;
    }

     function phpLekarzeToJsArray($input) {
        $js = "var lekarze = new Array();";

        foreach($input as $i=>$name) {
            $js .= "lekarze[".$i."] = '".$name."';";
        }

        return $js;
    }


    $today = time();
    $oneDay = 24 * 60 * 60;

    $week = array();
    $weekParsed = "[";
    $offset = 0; // 0 = today is Monday

    while(date('N', $today+$offset*$oneDay) != 1)
            $offset--;

    for($i = 0; $i < 7; $i++) {
        $week[$i] = $today+($offset+$i)*$oneDay;
        $weekParsed .= '\''.$week[$i].'\',';
    }
    $weekParsed = substr($weekParsed, 0, strlen($weekParsed)-1).']';

    $terminy = Wizyta::model()->getDostepneTerminy($week[0]);
    $l = Lekarz::model()->findAll();
    $lekarze = array();
    foreach ($l as $lekarz) {
        $lekarze[$lekarz->idLekarz] = $lekarz->fullName;
    }

    Yii::app()->clientScript->registerScript('globals', "
        var weekOffset = 0;
        ".phpTerminyToJsArray($terminy)
         .phpLekarzeToJsArray($lekarze)."
        var klik = function(event) {
                var g = event.target.parentNode.childNodes[0].id.split('_');
                var godzina = 4*parseInt(g[1]) + parseInt(g[2]);
                var dzien = event.target.cellIndex-1;
                var info = terminy[dzien][godzina];
                var dzienFull = $('th').get(dzien+1).innerHTML;
                var html = dzienFull + ', godz. ' + g[1] + ':' + (g[2] == 0 ? '00' : 15*g[2]) + '<br /><br /><u>Lekarze:</u><br/>';
                var idLekarz = $('#Wizyta_idLekarz').val()
                if (!info || (!info[idLekarz] && idLekarz))
                    html += 'brak';

                for (id in info) {
                    if (info[id] && (idLekarz == id || idLekarz == \"\")) {
                        if (info[id] == 'R') {
                            html += '(<span class=\'red\'>zajęty</span>) ' + lekarze[id] + '<br />';
                        } else if (info[id] == 'W') {
                            html += '(<span class=\'green\'>wolny</span>) ' + lekarze[id] + ' - '
                                 +'<a onclick=\"js:rezerwuj(\''+dzienFull.split('<br>')[1]+'\', \''+ g[1] + ':' + 15*g[2] +'\', \''+id+'\', \''+lekarze[id]+'\')\">Zarezerwuj!</a><br />';
                        }
                    }
                }

                $('#terminInfo').hide('blind', function() {
                    $('#terminInfoContent').html(html);
                    $('#terminInfo').show('blind');
                });
            }
            var nextW = function() {
                weekOffset++;
                $.ajax({
                    type: 'POST',
                    url: '".CController::createUrl('dynamicTerminy')."',
                    data: {'week': ".$weekParsed.", 'today': '".$today."', 'weekOffset': weekOffset, 'idLekarz': $(\"#filtrLekarze\").val()},
                    success: function(data) {
                        $('#tableContainer').html(data);
                        $('#terminTbody').click(function(event) {klik(event);});
                        $('#nextWeek').click(function(event) {nextW(event);});
                        $('#prevWeek').click(function(event) {prevW(event);});
                    }
                });
                
            }

            var prevW = function() {
                weekOffset--;
                $.ajax({
                    type: 'POST',
                    url: '".CController::createUrl('dynamicTerminy')."',
                    data: {'week': ".$weekParsed.", 'today': '".$today."', 'weekOffset': weekOffset},
                    success: function(data) {
                        $('#tableContainer').html(data);
                        $('#terminTbody').click(function(event) {klik(event);});
                        $('#nextWeek').click(function(event) {nextW(event);});
                        $('#prevWeek').click(function(event) {prevW(event);});
                    }
                });
                
            }
    ", CClientScript::POS_HEAD);
    
    Yii::app()->clientScript->registerScript('rezerwuj', "
        var rezerwuj = function(d, g, lId, lName) {
            g_ = g.split(':');
            $('#Wizyta_rejestracjaInfo').val(lName + ' (' + d + ', ' + g_[0] + ':' + ( g_[1] == '0' ? '00' : g_[1] ) + ')');
            $('#Wizyta_idLekarz').val(lId);
            $('#Wizyta_Termin').val(d + ' ' + g);
            $('#Wizyta_Submit').removeAttr('disabled');
        }
    ", CClientScript::POS_BEGIN);

    Yii::app()->clientScript->registerScript('main', "
        window.addEventListener('load', function() {
            var d = new Date();
            var h = d.getHours();
            
            var m = parseInt(d.getMinutes()/15);
            $('#terminTbody').scrollTo( $('#hour_'+h+'_'+m), 800 );
            $('#nextWeek').click(function(event) {nextW(event);});
            $('#prevWeek').click(function(event) {prevW(event);});
            $('#terminTbody').click(function(event) {klik(event);});
        }, false);
    ");

?>

	<p class="note">Pola oznaczone <span class="required">*</span> są wymagane.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo CHTML::label('Pacjent', 'pacjent'); ?>
		<?php echo CHTML::textField('Pacjent', $pacjent->Imie.' '.$pacjent->Nazwisko, array('disabled'=>'yes')); ?>
                <?php echo $form->hiddenField($model,'idPacjent',array('value'=>$pacjent->idPacjent));?>
	</div>

        <div class="row">
		<?php echo $form->labelEx($model,'rejestracjaInfo'); ?>
		<?php echo $form->textField($model,'rejestracjaInfo', array('disabled'=>'yes', 'size'=>50)); ?>
                <?php echo $form->hiddenField($model, 'idLekarz'); ?>
                <?php echo $form->hiddenField($model, 'Termin'); ?>
		<?php echo $form->error($model,'rejestracjaInfo'); ?>
	</div>
        <br />
	<div class="row">
		<?php echo CHTML::label('Pokaż terminy', 'filtrLekarze'); ?>
                <?php 
                    echo CHTML::dropDownList('filtrLekarze', '', CHtml::listData(Lekarz::model()->findAll(),'idLekarz','Fullname'), array(
                    'empty' => '(Wszystkich lekarzy)',
                    'ajax' => array(
                        'type'=>'POST', //request type
                        'url'=>CController::createUrl('dynamicTerminy'), //url to call.
                        'data'=>array('week'=>$week, 'today'=>$today, 'idLekarz'=>'js:jQuery("#filtrLekarze").val()'),
                        'success'=>'function(data) {
                            $(\'#tableContainer\').html(data);
                            $(\'#terminTbody\').click(function(event) {klik(event);});
                            $(\'#nextWeek\').click(function(event) {nextW(event);});
                            $(\'#prevWeek\').click(function(event) {prevW(event);});
                        }', //selector to update
                    )
                )); ?>
		<?php echo $form->error($model,'idLekarz'); ?>
	</div>

        <?php
        echo "<div id='tableContainer'><table class='scrollTable'><thead class='fixedHeader'><tr><th id='prevWeek' class='hour'>";
        foreach($week as $day) {
            echo "<th".($day==$today?" class='today'":"")."><span>".Wizyta::model()->dayPL(date('N', $day))."</span><br />"
                 .date('j', $day)." ".Wizyta::model()->monthPL(date('n', $day))." ".date('Y', $day)."</th>";
        }
        echo "<th id='nextWeek' class='filler'></th></tr></thead><tbody id='terminTbody' class='scrollContent'>";
        for($i = 0; $i < 96; $i++) {
            //echo "<tr><td class='hour'>".(($i-$i%4)/4).":".($i%4==0?"00":$i%4*15)."</td>";
            echo "<tr><td class='hour' id='hour_".(($i-$i%4)/4)."_".($i%4)."'>".(($i%4==0) ? ($i/4).":00" : "")."</td>";
            $j = 0;
            foreach($week as $day) {
                if (isset($terminy[$j][$i])) {
                    $class = " reserved";
                    foreach ($terminy[$j][$i] as $l) {
                        if ($l == 'W') {
                            $class = " free";
                        }
                    }
                } else {
                    $class = "";
                }
                echo "<td class='norm".($day==$today?" today":"")
                     .$class."'></td>";
                $j++;
            }
            echo "</tr>";
        }
        echo "</tbody></table></div>";
?>

	<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Zarezerwuj' : 'Zatwierdź zmiany',  array('disabled'=>'yes', 'id'=>'Wizyta_Submit')); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->